/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package storymotion.photo;

import storymotion.keyword.Keyword;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import storymotion.dao.DAO;
import storymotion.user.User;

/**
 *
 * @author Leonardo Oliveira Moreira
 */
public class PhotoDAO extends DAO {

    public PhotoDAO() throws SQLException {
    }

    public long getNewId() throws SQLException {
        long result = -1;
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT nextval('photo_id_seq') AS id;");
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                result = resultSet.getLong("id");
            }
            resultSet.close();
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
        return result;
    }

    public void insert(Photo photo) throws SQLException {
        if (photo == null || photo.getName() == null || photo.getExtension() == null || photo.getDate() == null || photo.getUserId() == null || photo.getName().trim().length() == 0 || photo.getExtension().trim().length() == 0) {
            throw new SQLException("Could not perform this action");
        }
        try {
            String sqlWithId = "INSERT INTO photo (id, name, extension, date, user_id) VALUES (?, ?, ?, ?, ?)";
            String sqlWithoutId = "INSERT INTO photo (name, extension, date, user_id) VALUES (?, ?, ?, ?)";
            PreparedStatement preparedStatement = null;
            if (photo.getId() != null) {
                preparedStatement = connection.prepareStatement(sqlWithId);
                preparedStatement.setLong(1, photo.getId());
                preparedStatement.setString(2, photo.getName());
                preparedStatement.setString(3, photo.getExtension());
                preparedStatement.setTimestamp(4, new java.sql.Timestamp(photo.getDate().getTime()));
                preparedStatement.setLong(5, photo.getUserId());
            } else {
                preparedStatement = connection.prepareStatement(sqlWithoutId);
                preparedStatement.setString(1, photo.getName());
                preparedStatement.setString(2, photo.getExtension());
                preparedStatement.setTimestamp(3, new java.sql.Timestamp(photo.getDate().getTime()));
                preparedStatement.setLong(4, photo.getUserId());
            }
            int result = preparedStatement.executeUpdate();
            if (result != 1) {
                throw new SQLException("Could not perform this action");
            }
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public void insert(Keyword keyword) throws SQLException {
        if (keyword == null || keyword.getPhotoId() == null || keyword.getKeyword() == null || keyword.getKeyword().trim().length() == 0) {
            throw new SQLException("Could not perform this action");
        }
        try {
            PreparedStatement preparedStatement = null;
            preparedStatement = connection.prepareStatement("INSERT INTO keywords (photo_id, keyword) VALUES (?, ?)");
            preparedStatement.setLong(1, keyword.getPhotoId());
            preparedStatement.setString(2, keyword.getKeyword());
            int result = preparedStatement.executeUpdate();
            if (result != 1) {
                throw new SQLException("Could not perform this action");
            }
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public void update(Photo photo) throws SQLException {
        if (photo == null || photo.getId() == null || photo.getName() == null || photo.getExtension() == null || photo.getDate() == null || photo.getUserId() == null || photo.getName().trim().length() == 0 || photo.getExtension().trim().length() == 0) {
            throw new SQLException("Could not perform this action");
        }
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("UPDATE photo SET name = ?, extension = ?, date = ?, user_id = ? WHERE id = ?");
            preparedStatement.setString(1, photo.getName());
            preparedStatement.setString(2, photo.getExtension());
            preparedStatement.setTimestamp(3, new java.sql.Timestamp(photo.getDate().getTime()));
            preparedStatement.setLong(4, photo.getUserId());
            preparedStatement.setLong(5, photo.getId());
            int result = preparedStatement.executeUpdate();
            if (result != 1) {
                throw new SQLException("Could not perform this action");
            }
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public void delete(long id) throws SQLException {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM photo WHERE id = ?");
            preparedStatement.setLong(1, id);
            int result = preparedStatement.executeUpdate();
            if (result != 1) {
                throw new SQLException("Could not perform this action");
            }
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public List<Photo> get(Photo photo) {
        List<Photo> result = new ArrayList<Photo>();

        return result;
    }

    public Photo getById(long id) throws SQLException {
        Photo photo = null;
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT id, name, extension, date, user_id FROM photo WHERE id = ?");
            preparedStatement.setLong(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                photo = new Photo();
                photo.setId(resultSet.getLong("id"));
                photo.setName(resultSet.getString("name"));
                photo.setExtension(resultSet.getString("extension"));
                photo.setDate(new Date(resultSet.getTimestamp("date").getTime()));
                photo.setUserId(resultSet.getLong("user_id"));
            }
            resultSet.close();
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
        return photo;
    }

    public List<Photo> getByUserId(long userId) throws SQLException {
        if (userId < 1) {
            throw new SQLException("Could not perform this action");
        }
        List<Photo> result = new ArrayList<Photo>();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT id, name, extension, date, user_id FROM photo WHERE user_id = ?");
            preparedStatement.setLong(1, userId);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Photo photo = new Photo();
                photo.setId(resultSet.getLong("id"));
                photo.setName(resultSet.getString("name"));
                photo.setExtension(resultSet.getString("extension"));
                photo.setDate(new Date(resultSet.getTimestamp("date").getTime()));
                photo.setUserId(resultSet.getLong("user_id"));
                result.add(photo);
            }
            resultSet.close();
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
        return result;
    }

    public List<Keyword> getKeywordsByPhotoId(long photoId) throws SQLException {
        if (photoId < 1) {
            throw new SQLException("Could not perform this action");
        }
        List<Keyword> result = new ArrayList<Keyword>();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT photo_id, keyword FROM keywords WHERE photo_id = ?");
            preparedStatement.setLong(1, photoId);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Keyword keyword = new Keyword();
                keyword.setPhotoId(resultSet.getLong("photo_id"));
                keyword.setKeyword(resultSet.getString("keyword"));
                result.add(keyword);
            }
            resultSet.close();
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
        return result;
    }

    public List<PhotoUser> getPhotosByKeyword(String keyword) throws SQLException {
        if (keyword == null || keyword.trim().length() == 0) {
            throw new SQLException("Could not perform this action");
        }
        List<PhotoUser> result = new ArrayList<PhotoUser>();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT p.id, p.name, p.extension, p.date, p.user_id, u.name as user_name FROM photo p, keywords k, \"user\" u WHERE p.id = k.photo_id AND u.id = p.user_id AND LOWER(k.keyword) = ?");
            preparedStatement.setString(1, keyword.trim().toLowerCase());
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                PhotoUser photoUser = new PhotoUser();
                photoUser.setId(resultSet.getLong("id"));
                photoUser.setName(resultSet.getString("name"));
                photoUser.setExtension(resultSet.getString("extension"));
                photoUser.setDate(new Date(resultSet.getTimestamp("date").getTime()));
                photoUser.setUserId(resultSet.getLong("user_id"));
                User owner = new User();
                owner.setId(resultSet.getLong("user_id"));
                owner.setName(resultSet.getString("user_name"));
                photoUser.setOwner(owner);
                result.add(photoUser);
            }
            resultSet.close();
            preparedStatement.close();
        } catch (SQLException ex) {
            throw ex;
        }
        return result;
    }
}
